package com.mapapp.flutter_mapapp.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mapapp.flutter_mapapp.R;
import com.mapapp.flutter_mapapp.adapter.PhotoAdapter;
import com.mapapp.flutter_mapapp.service.AudioRecordService;
import com.mapapp.flutter_mapapp.util.HorizontalSpaceItemDecoration;
import com.mapapp.flutter_mapapp.util.ScreenUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PhotoRecordActivity extends ImmersiveBaseActivity implements View.OnClickListener {
    private static final String TAG = "PhotoRecordActivity";
    @BindView(R.id.bt_photo_start)
    Button btPhotoStart;
    @BindView(R.id.iv_photo_gate)
    ImageView ivPhotoGate;
    @BindView(R.id.bt_photo_stop)
    Button btPhotoStop;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.rv_photo_list)
    RecyclerView rvPhotoList;
    @BindView(R.id.btn_error_correction)
    Button btnErrorCorrection;

    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private File tempFile;
    private Dialog mDialog;
    private static final int PHOTO_GATE = 11;// 门牌图片
    private static final int PHOTO_RECY = 21;// 列表图片
    private int PhotoType = 0;
    private List<Bitmap> mPhotos = new ArrayList<>();
    private PhotoAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_record);
        ButterKnife.bind(this);

        mContext = this;
        setListener();

        LinearLayoutManager llmanage = new LinearLayoutManager(this);
        llmanage.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvPhotoList.setLayoutManager(llmanage);
        rvPhotoList.addItemDecoration(new HorizontalSpaceItemDecoration(60));
        mAdapter = new PhotoAdapter(mPhotos, this);
        rvPhotoList.setAdapter(mAdapter);
    }

    private void setListener() {
        btPhotoStart.setOnClickListener(this);
        ivPhotoGate.setOnClickListener(this);
        btPhotoStop.setOnClickListener(this);
        btnAddPhoto.setOnClickListener(this);
        btnErrorCorrection.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.bt_photo_start:
                if(AudioRecordService.getIsServerRun()){
                    intent = new Intent(mContext, AudioRecordService.class);
                    startService(intent);
                }
                takePhoto();
                break;
            case R.id.iv_photo_gate:
                PhotoType = PHOTO_GATE;
                showPickPhotoDialog();
                break;
            case R.id.bt_photo_stop:
                intent = new Intent(mContext, AudioRecordService.class);
                stopService(intent);
                break;
            case R.id.take_photo_tv:
                takePhoto();
                break;
            case R.id.album_tv:
                intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,
                        PHOTO_REQUEST_GALLERY);
                mDialog.dismiss();
                break;
            case R.id.cancel_tv:
                if (mDialog.isShowing())
                    mDialog.dismiss();
                break;
            case R.id.btn_add_photo:
                PhotoType = PHOTO_RECY;
                showPickPhotoDialog();
                break;
            case R.id.btn_error_correction:
                PopupMenu popupMenu = new PopupMenu(PhotoRecordActivity.this, v);
                popupMenu.getMenuInflater().inflate(R.menu.error_correction, popupMenu.getMenu());
                popupMenu.show();
                break;
        }
    }

    private void takePhoto() {
        Intent intent = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        tempFile = new File(Environment
                .getExternalStorageDirectory(), "tmp.jpg");
        // 从文件中创建uri

        if (Build.VERSION.SDK_INT >= 24) {
            Uri photoUri =
                    FileProvider.getUriForFile(mContext, "com.mapapp.flutter_mapapp", tempFile);
            //临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
        } else {
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        File outputFile = new File("/mnt/sdcard/tupian_out.jpg");//裁切后输出的图片
        if (resultCode == Activity.RESULT_CANCELED) {

            return;
        } else {
            if (requestCode == PHOTO_REQUEST_GALLERY) {
                if (data != null) {
                    Uri uri = data.getData();
                    cropImageUri(uri, 200, 200, PHOTO_REQUEST_CUT, outputFile);
                } else {
                    Toast.makeText(mContext, "图片获取失败", Toast.LENGTH_SHORT);
                }

            } else if (requestCode == PHOTO_REQUEST_CAMERA) {
                Uri imageUri =
                        FileProvider.getUriForFile(mContext, "com.mapapp.flutter_mapapp", tempFile);
                cropImageUri(imageUri, 200, 200,
                        PHOTO_REQUEST_CUT, outputFile);

            } else if (requestCode == PHOTO_REQUEST_CUT) {
                Log.i(TAG, "requestCode == PHOTO_REQUEST_CUT");
                try {
                    // 将临时文件删除
                    if (tempFile != null) {
                        tempFile.delete();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Uri uri = Uri.fromFile(outputFile);
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                    if (PhotoType == PHOTO_GATE) {
                        ivPhotoGate.setImageBitmap(bitmap);
                    } else if (PhotoType == PHOTO_RECY) {
                        mPhotos.add(bitmap);
                        mAdapter.notify(mPhotos);
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 剪切图片
     *
     * @param uri
     * @function:
     * @author:Jerry
     * @date:2013-12-30
     */

    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode, File outputFile) {
        Intent intent = new Intent("com.android.camera.action.CROP");

        if (Build.VERSION.SDK_INT >= 24) {
            //临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, "image/*");
        } else {
            intent.setDataAndType(uri, "image/*");
        }

        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        //return-data为true时，直接返回bitmap，可能会很占内存，不建议，小米等个别机型会出异常！！！
        //所以适配小米等个别机型，裁切后的图片，不能直接使用data返回，应使用uri指向
        //裁切后保存的URI，不属于我们向外共享的，所以可以使用fill://类型的URI
        Uri outputUri = Uri.fromFile(outputFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("return-data", false);

        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, requestCode);
    }

    private void showPickPhotoDialog() {
        hintKbTwo();
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_pick_photo, null);
        TextView takePhoto = (TextView) view.findViewById(R.id.take_photo_tv);
        TextView albumTv = (TextView) view.findViewById(R.id.album_tv);
        TextView cancelTv = (TextView) view.findViewById(R.id.cancel_tv);
        takePhoto.setOnClickListener(this);
        albumTv.setOnClickListener(this);
        cancelTv.setOnClickListener(this);
        mDialog = new Dialog(this, R.style.pickPhotoDialog);
        mDialog.setContentView(view);

        if (!mDialog.isShowing()) {
            Window dialogWindow = mDialog.getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setWindowAnimations(R.style.pickPhoto_dialogAnim);
            lp.width = ScreenUtil.getScreenWidth(mContext);
            dialogWindow.setGravity(Gravity.BOTTOM);
            mDialog.show();
        }
    }


}
